package com.livra.examples.pickwebvoter.tags;

import java.io.IOException;
import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;

@SuppressWarnings("unchecked")
public class SimpleSelectMapTag extends TagSupport {
    /**
     * 
     */
    private static final long serialVersionUID = 1L;
    private String mapObject;
    private String name;
    
    public void setName(String name) {
        this.name = name;
    }

    public void setMapObject(String mapObject) {
        this.mapObject = mapObject;
    }

    
    public int doStartTag() throws JspException {
        HttpServletRequest request = (HttpServletRequest) pageContext
                .getRequest();
        JspWriter out = pageContext.getOut();

        Map<String,String> map = (Map<String,String>) request.getAttribute(this.mapObject);
        StringBuilder selectBuilder = new StringBuilder();
        selectBuilder.append("<select name=\"").append(name).append("\" >");
        if (map != null) {
            for (Entry<String,String> key : map.entrySet()) {
                selectBuilder.append("<option value=\"").append(key.getKey())
                        .append("\">").append(key.getValue()).append(
                                "</option>");
            }
        }
        selectBuilder.append("</select>");
        try {
            out.write(selectBuilder.toString());
        } catch (IOException e) {
            e.printStackTrace();
        }
        
        return EVAL_PAGE;
    }
}
